import constants from "@common/api/constants";
import common from "@common/api/common";
// import { Toast } from 'vant';

const uploadSlide = (options, setting) => {
    let begin = (new Date()).getTime();
    let slice = options.base64.substr(setting.sliceSize * setting.index + setting.skip, setting.sliceSize);
    let subData = {
        slice: slice,
        sliceIndex: setting.index,
        sliceSize: setting.sliceSize,
        totalLength: setting.total,
        fileInfoId: setting.sid,
        fileType: setting.ext,
        fileName: setting.fileName,
        associate_biz_table: options.associate_biz_table,
        associate_biz_sid: options.associate_biz_sid,
        associate_biz_field_tag: options.associate_biz_field_tag,
        // showToast: false,
    }
    return common.requestData(constants.File_UploadFileBase64Slice, subData).then(res => {
        let fileInfo = res.data;
        if (fileInfo) {
            if (fileInfo.state === -999) {
                // Toast.clear();
                return res;
            } else {
                let percent = (fileInfo.state * 100 / (setting.total / setting.sliceSize + 1)).toFixed(0) + "%";
                // toast.message = '上传中...' + percent + "";
                if (setting.index === 0 && setting.sliceSize === 102400 && setting.total / setting.sliceSize > 20) {
                    //测试第一个片段的上传时间，如果小于1秒并且片段数量大于20才进行片段大小调整
                    // 则片段增加到每秒钟一次的速度,最大是16个100K长度
                    let end = (new Date()).getTime();
                    if (end - begin < 3000) {
                        let ratio = (3000 / (end - begin)).toFixed(0);
                        if (ratio > 16) {
                            ratio = 16;
                        }
                        setting.sliceSize = setting.sliceSize * ratio;
                    } else {
                        setting.index = fileInfo.state;
                    }
                } else {
                    setting.index = fileInfo.state;
                }
                setting.sid = fileInfo.sid;
                return uploadSlide(options, setting);
            }
        }
    })
};
const uploadBase64Slice = (options) => {
    if (!options.sliceSize) {
        options.sliceSize = 102400;
    }
    let prefStr = options.base64.substring(0, 100);
    let pos1 = prefStr.indexOf("/");
    let pos2 = prefStr.indexOf(";");
    let fileType = '';
    if (pos1 > -1 && pos2 > -1 && pos2 > pos1) {
        fileType = prefStr.substring(pos1 + 1, pos2);
    }
    let skipCount = options.base64.indexOf(';base64,') + 8;
    let totalSize = options.base64.length - skipCount;
    // const toast = Toast.loading({
    //     duration: 0,
    //     forbidClick: true,
    //     message: '上传中...'
    // });
    return uploadSlide(options, {
        id: null,
        index: 0,
        sliceSize: options.sliceSize,
        skip: skipCount,
        total: totalSize,
        ext: fileType
    });
};
export default {
    uploadBase64Slice,
};
